package com.atguigu.tingshu.order.pattern.impl;

import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.pattern.PayStrategy;
import com.atguigu.tingshu.order.service.OrderDetailService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName : BalancePay
 * Package : com.atguigu.tingshu.order.pattern.impl
 * Description :
 * <p>
 * Author: LHZ
 * Create: 2025/8/4 15:36
 * Version: 1.0
 */
@Slf4j
@SuppressWarnings("all")
@Component(SystemConstant.ORDER_PAY_ACCOUNT)
public class BalancePay implements PayStrategy {

    @Autowired
    private AccountFeignClient accountFeignClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void submitOrder(Long userId, OrderInfo orderInfo) {
        //余额支付
        //远程调用扣减账户余额 AccountDeductVo
        AccountDeductVo accountDeductVo = new AccountDeductVo();
        accountDeductVo.setOrderNo(orderInfo.getOrderNo());
        accountDeductVo.setUserId(orderInfo.getUserId());
        accountDeductVo.setAmount(orderInfo.getOrderAmount());
        accountDeductVo.setContent(orderInfo.getOrderTitle());

        Result result = accountFeignClient.checkAndDeduct(accountDeductVo);
        if(result.getCode().intValue() != 200){
            // 扣减余额失败，业务终止，回滚全局事务
            throw new GuiguException(result.getCode(), result.getMessage());
        }
        //扣减余额成功 将数据库中的订单信息进行修改
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
        orderInfoMapper.updateById(orderInfo);

        //支付成功后调用远程服务进行虚拟发货
        UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
        userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
        userPaidRecordVo.setUserId(orderInfo.getUserId());
        userPaidRecordVo.setItemType(orderInfo.getItemType());
        List<OrderDetail> orderDetailList = orderDetailService.list(
                new LambdaQueryWrapper<OrderDetail>()
                        .eq(OrderDetail::getOrderId, orderInfo.getId())
                        .select(OrderDetail::getItemId)
        );
        List<Long> itemIdList = orderDetailList.stream().map(OrderDetail::getItemId).collect(Collectors.toList());
        userPaidRecordVo.setItemIdList(itemIdList);

        if(!CollectionUtils.isEmpty(orderDetailList)){

            result = userFeignClient.savePaidRecord(userPaidRecordVo);
            if(result.getCode().intValue() != 200){
                log.error("虚拟发货失败");
                throw new GuiguException(result.getCode(),result.getMessage());
            }
        }

    }
}